package br.com.mmca.admrespaco.business;

import java.math.BigDecimal;
import java.lang.ArithmeticException;
import javax.inject.Inject;

import br.gov.frameworkdemoiselle.annotation.Startup;
import br.gov.frameworkdemoiselle.message.MessageContext;
import br.gov.frameworkdemoiselle.stereotype.BusinessController;
import br.gov.frameworkdemoiselle.template.DelegateCrud;
import br.gov.frameworkdemoiselle.transaction.Transactional;

import br.com.mmca.admrespaco.domain.Espaco;
import br.com.mmca.admrespaco.persistence.EspacoDAO;

import br.com.mmca.admrespaco.message.ErrorMessages;
import br.com.mmca.admrespaco.message.InfoMessages;

@BusinessController
public class EspacoBC extends DelegateCrud<Espaco, Long, EspacoDAO> {
	
	private static final long serialVersionUID = 1L;
	
	private boolean erro;
	
	@Inject
	private MessageContext msg;
	 
	@Startup
	@Transactional
	public void load() {
		if (findAll().isEmpty()) {
			BigDecimal val = new BigDecimal(545.00d);
			insert(new Espaco("Salao de Festas Adulto", val));
			insert(new Espaco("Salao de Festas Infantil", val));
				}
	}
	 
	@Override
	@Transactional
	public void insert(final Espaco se) 
	{
		validateFields(se);
		if (! erro) 
		{
		  super.insert(se);
		  msg.add(InfoMessages.espaco_insert_ok, se.getNome());
		}
		
	}
	@Override
	@Transactional
	public void update(final Espaco se) 
	{
		validateFields(se);
		if (! erro) 
		{
		  super.update(se);
		  msg.add(InfoMessages.espaco_update_ok, se.getNome());
		}
	}
	
	@Override
	@Transactional
	public void delete(final Long id) 
	{
		 super.delete(id);
		 msg.add(InfoMessages.espaco_delete_ok, id);
	}
	
	private void validateFields(final Espaco se) 
	{
		erro=false;
		try
		{
		if(se.getValor().intValueExact()== 0)
		  {
			erro=true;
			msg.add(ErrorMessages.espaco_valor_nok, se.getValor());
			return;
		  }
		 }catch (ArithmeticException e) {
			
		 }
	}
}
